<template>
  <div class="container">
    <headerBar :title="local.saleOrderDetail" @changeLan="changeLan" @pageReturn="pageReturn"></headerBar>
    <div class="all" :style="{paddingTop: pdt+'px'}">
      <div class="stock-detail-panel">
        <div class="jt_flex jt_flex_dr mb_6">
          <span
            class="jt_flex form_label jt_flex_der name"
            :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_120'"
            style="justify-content: flex-end;"
          >
            <span style="color: red;">*</span>
            {{local.salesOrderNo}}：
          </span>
          <div class="jt_flex jt_flex_der form_input">
            <input
              disabled
              :placeholder="local.automaticallygeneratedbythesystem"
              v-model="objSale.orderCode"
            />
          </div>
        </div>
        <div class="jt_flex jt_flex_dr mb_6">
          <span
            class="jt_flex form_label jt_flex_der"
            :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_120'"
            style="justify-content: flex-end;"
          >{{local.businessDate}}：</span>
          <div class="btn">
            <div class="btn">{{busDateFormat}}</div>
          </div>
        </div>
        <div class="jt_flex jt_flex_dr mb_6">
          <span
            class="jt_flex form_label jt_flex_der"
            :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            style="justify-content: flex-end;"
          >{{local.orderStatus}}：</span>
          <div class="btn">
            <span class="btn">{{objSale.status=='SAVE'?local.saved: local.reviewed}}</span>
          </div>
        </div>
      </div>
      <div class="top">
        <div class="stock-detail-panel">
          <div class="jt_flex jt_flex_dr">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >
              <span style="color: red;">*</span>
              {{local.customer}}：
            </div>
            <div class="jt_flex jt_flex_der w_calc_70 form_input bt_1">
              <picker
                class="weui-btn"
                style="width: 100%"
                @change="PickerChange"
                :value="indexPicker"
                :range="array"
                :range-key="'customerName'"
                :disabled="enable"
              >
                <input
                  type="default"
                  class="jt_flex"
                  v-model="objSale.customerName"
                  disabled
                  :placeholder="local.choose"
                />
                <!--  -->
              </picker>
              <span class="unit jt_flex">▼</span>
            </div>
          </div>
        </div>
      </div>
      <div class="top">
        <div class="stock-detail-panel">
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_120'"
            >{{local.logisticsOrderNo}}：</div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex: 1;border-bottom: 2rpx solid #000;"
            >
              <picker
                class="weui-btn"
                @change="PickerCodeChange"
                :value="indexCodePicker"
                :range="checkedGoodsList"
                :range-key="'trackNumber'"
                style="flex:1;"
                :disabled="loggisticsNoEnable"
              >
                <input
                  type="default"
                  v-model="trackNumber"
                  disabled
                  :placeholder="trackNumber == ''?local.empty:local.choose"
                />
              </picker>
              <span class="unit">▼</span>
            </div>
          </div>
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >
              <span style="color: red;">*</span>
              {{local.salesInvoiceNo}}：
            </div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex:1;border-bottom: 2rpx solid #000;"
            >
              <input
                v-model="objSale.saleOrderInvoice"
                :placeholder="objSale.saleOrderInvoice == ''?local.empty:local.peleaseEnter"
                :disabled="enable"
              />
            </div>
          </div>
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.invoiceDate}}：</div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex:1;border-bottom: 2rpx solid #000;"
            >
              <picker
                class="weui-btn"
                mode="date"
                :value="objSale.invoiceDate"
                start="1999-01-01"
                end="2099-01-01"
                @change="TimeChange"
                :disabled="enable"
              >
                <input
                  v-model="invoiceDateFormat"
                  :placeholder="objSale.invoiceDate == null ? local.empty:local.peleaseEnter"
                  disabled
                />
              </picker>
            </div>
          </div>
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_120'"
            >{{local.totalPrice}}：</div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex:1;border-bottom: 2rpx solid #000;"
            >
              <input
                v-model="objSale.totalPrice"
                :placeholder="local.peleaseEnter"
                :disabled="enable"
              />
            </div>
          </div>
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.paymentStatus}}：</div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex:1;border-bottom: 2rpx solid #000;"
            >
              <picker
                class="weui-btn"
                :value="indexPayment"
                :range="paymentStatusList"
                :range-key="'dictLabel'"
                @change="paymentStatusChange"
                :disabled="enable"
              >
                <input v-model="paymentStatusLabel" :placeholder="local.choose" disabled />
              </picker>
            </div>
          </div>
        </div>
      </div>
      <!-- 选中的商品 -->
      <div v-for="(item, i) in selectGoodsList" :key="i">
        <div class="stock-detail-panel">
          <div class="opreate jt_flex jt_flex_row_right">
            <div
              class="open"
              @click="openOrClose(selectGoodsList,i)"
            >{{item.open ? local.fold : local.unfold}}</div>
            <div
              class="detele-text"
              @click="deleteRow(selectGoodsList,i)"
              v-if="!enable"
            >{{local.deletesingle}}</div>
          </div>
          <div class="jt_flex jt_flex_dr mb_6">
            <div
              class="jt_flex form_label jt_flex_der"
              :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
            >{{local.goodsName}}：</div>
            <div class="names-goods">{{item.goodsName}}</div>
          </div>
          <div class="jt_flex jt_flex_dr mb_6">
            <div
              class="jt_flex form_label jt_flex_der"
              :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
            >{{local.buyArea}}：</div>
            <div class="names-goods">{{item.buyAreaName ||''}}</div>
          </div>
          <div class="jt_flex jt_flex_dr mb_6">
            <div
              class="jt_flex form_label jt_flex_der"
              :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
            >{{local.warehouseOut}}：</div>
            <div class="names-goods">{{item.warehouseName}}</div>
          </div>
        </div>
        <block v-if="item.open">
          <div class="select-photo">
            <div class="a">{{local.photosBeforeAcceptance}}</div>
            <div class="b">
              <div class="page">
                <div class="weui-uploader__bd">
                  <div class="weui-uploader__files" id="uploaderFiles">
                    <block v-for="(ite, index) in item.beginPicUrlList" :key="index">
                      <div
                        class="weui-uploader__file"
                        @click="predivImageBegin"
                        :data-urls="item.beginPicUrlList"
                        :id="ite"
                      >
                        <img class="weui-uploader__img" :src="Shop+ite" mode="aspectFill" />
                      </div>
                    </block>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="stock-detail-panel">
            <div class="jt_flex jt_flex_dr mb_6">
              <div
                class="jt_flex form_label jt_flex_der jt_flex_row_right"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.grade}}：</div>
              <div class="names-goods">{{item.goodsLevelName}}</div>
            </div>
            <div class="jt_flex jt_flex_dr mb_6">
              <div
                class="jt_flex form_label jt_flex_der jt_flex_row_right"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.beltType}}：</div>
              <div class="names-goods">{{item.beltTypeName}}</div>
            </div>
          </div>
          <div class="stock-detail-panel">
            <div class="jt_flex jt_flex_dr mb_6">
              <span
                class="jt_flex form_label jt_flex_der jt_flex_row_right"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.thickness}}：</span>
              <div
                class="jt_flex jt_flex_der form_input w_calc_70 bt_1"
                style="position: relative;"
              >
                <input :placeholder="local.peleaseEnter" disabled v-model="item.sizeHeight" />
                <span class="unit">MM</span>
              </div>
            </div>
            <div class="jt_flex jt_flex_dr mb_6">
              <span
                class="jt_flex form_label jt_flex_der jt_flex_row_right"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.width}}：</span>
              <div
                class="jt_flex jt_flex_der form_input w_calc_70 bt_1"
                style="position: relative;"
              >
                <input :placeholder="local.peleaseEnter" disabled v-model="item.sizeWidth" />
                <span class="unit">MM</span>
              </div>
            </div>
            <div class="jt_flex jt_flex_dr mb_6">
              <span
                class="jt_flex form_label jt_flex_der jt_flex_row_right"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.length}}：</span>
              <div
                class="jt_flex jt_flex_der form_input w_calc_70 bt_1"
                style="position: relative;"
              >
                <input :placeholder="local.peleaseEnter" disabled v-model="item.sizeLong" />
                <span class="unit">M</span>
              </div>
            </div>
            <div class="jt_flex jt_flex_dr mb_6">
              <span
                class="jt_flex form_label jt_flex_der jt_flex_row_right"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.weight}}：</span>
              <div
                class="jt_flex jt_flex_der form_input w_calc_70 bt_1"
                style="position: relative;"
              >
                <input :placeholder="local.peleaseEnter" disabled v-model="item.weight" />
                <span class="unit">T</span>
              </div>
            </div>
          </div>
          <div class="select-photo">
            <div class="a">{{local.photosAfterAcceptance}}</div>
            <div class="b">
              <div class="page">
                <div class="weui-uploader__bd">
                  <div class="weui-uploader__files" id="uploaderFiles">
                    <block v-for="(ite, index) in item.endPicUrlList" :key="index">
                      <div
                        class="weui-uploader__file"
                        @click="predivImageEnd"
                        :id="ite"
                        :data-urls="item.endPicUrlList"
                      >
                        <img class="weui-uploader__img" :src="Shop+ite" mode="aspectFill" />
                      </div>
                    </block>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </block>
      </div>
      <div class="remark">
        <div>{{local.remark}}:</div>
        <textarea
          v-model="this.remark"
          :disabled="objSale.status=='SAVE'?false:true"
          style="height: 100rpx;max-width: 879rpx;resize: none;padding-left: 18rpx;"
        ></textarea>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-bar" v-if="objSale.status=='SAVE'">
      <div
        class="sum"
        @click="routerToUrl('../../pages/selectGoods/index?page='+'sale')"
      >+ {{local.addSaleGood}}</div>
      <div class="confirm" @click="confirm()">{{local.confirm}}</div>
    </div>
  </div>
</template>

<script>
import card from '@/components/card'
import home from '@/api/home'
import headerBar from '@/components/headerBar'
import { dictMatching, previewImage } from '@/utils/index'
import Shop from '../../../../config/shop'
var a
export default {
  components: {
    card,
    headerBar
  },
  onShow(){
    this.initLang()
    //上一页返回的数据
    if (a) {
      a = false
      return
    } else {
      this.initMyData()
    }
  },
  onLoad (options) {
    this.initLang()
    this.initData(options)
    this.pdt = this.globalData.CustomBar // 导航
    this.getId = options.id
  },
  computed:{
    busDateFormat(){
      const { busDate } =this.objSale
      return busDate ? wx.$timeFormat(busDate) : '' //new Date(busDate).$format('dd/MM/yyyy') : ''
    },
    invoiceDateFormat(){
      const { invoiceDate } =this.objSale
        return invoiceDate ? wx.$timeFormat(invoiceDate) : '' //new Date(invoiceDate).$format('dd/MM/yyyy') :''
    }
  },
  methods: {
    initLang(){
      this.local = wx.getStorageSync('local')
      this.lang = wx.getStorageSync('lang')
    },
    initData(options){
      this.checkedGoodsList = [{trackNumber: this.local.empty,goodsList: []}]
      this.getLogisicOrder() // 物流单号列表
      this.getCustomerList() // 客户列表
      this.getSaleOrderById(options.id)
    },
    initMyData(){
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1]; //当前页面
      let myData = currPage.data.mydata;
      this.mydata.selectGoodsItem = myData ? myData.selectGoodsItem : []
      if(myData){
        let item = this.mydata.selectGoodsItem
        item.open = false //默认折叠
        item.loggisticsGoods = 2 //选择的销售商品
        item.goodsLevelName = dictMatching(wx.getStorageSync('goodsLevel') || [],item.goodsLevel)
        item.beltTypeName = dictMatching(wx.getStorageSync('beltType') || [], item.beltType)
        item.beginPicUrlList = item.beginPicUrl == null ? []:item.beginPicUrl.split(',')
        item.endPicUrlList = item.endPicUrl == null ? []: item.endPicUrl.split(',')
        this.selectGoodsList.push(item)
        this.goodsCount = this.selectGoodsList.length
      }
    },
    TimeChange (e) {
      this.objSale.invoiceDate = e.mp.detail.value
    },
    deleteRow(list,index){
      let goodsList = wx.getStorageSync('selectGoodsIdList')
      let newList = goodsList.filter(item => item !== list[index].id)
      wx.setStorageSync('selectGoodsIdList',newList)
      list.splice(index,1)
      
    },
    openOrClose(list, index) {
      list[index].open = !list[index].open
      list.push()
    },
     paymentStatusChange(e){
      this.indexPayment = e.mp.detail.value
      this.paymentStatus = e.mp.detail.value
      this.paymentStatusLabel = this.paymentStatusList[e.mp.detail.value].dictLabel
    },
    //获取详情页的信息
    async getSaleOrderById (id) {
      const data = await home.getSaleOrderById({id: id})
      this.objSale = data
      this.objSale.busDate = data.busDate == null ? '':data.busDate.substring(0,10)
      this.objSale.invoiceDate = data.invoiceDate == null ? '':data.invoiceDate.substring(0,10)
      this.enable = data.status == 'PASS'?true:false
      this.indexPayment = data.paymentStatus == null ? null:this.paymentStatusList.findIndex(item => item.dictValue == data.paymentStatus)
      this.paymentStatusLabel =  data.paymentStatus == null ? '':dictMatching(wx.getStorageSync('paymentStatus') || [],data.paymentStatus)
      if(data.status == 'PASS' || this.checkedGoodsList.length == 0){
        //已审核或没有物流下拉列表时，禁用选择器
        this.loggisticsNoEnable = true
        //详情的物流单号为空时，输入框：显示 空
        if(data.trackNumber == this.local.empty || data.trackNumber == "null"){
          this.trackNumber = this.local.empty
        }else {
          this.trackNumber = data.trackNumber
        }
      }else {
        this.loggisticsNoEnable = false
         //详情的物流单号为空时，选择器：显示 请选择
        if(data.trackNumber == this.local.empty || data.trackNumber == "null"){
          this.trackNumber = this.local.option
        }else {
          this.trackNumber = data.trackNumber
        }
      }   
     
      this.indexPicker = this.array.findIndex(item => item.customerName == data.customerName)
      this.customerId = data.customerId
      this.objSale.customerName = data.customerName 
      data.goodsList.map(item => {
        item.open = false
        item.beginPicUrlList = item.beginPicUrl == null ? []: item.beginPicUrl.split(',')
        item.endPicUrlList = item.endPicUrl == null ? [] : item.endPicUrl.split(',')
        item.goodsLevelName = dictMatching(wx.getStorageSync('goodsLevel') || [],item.goodsLevel)
        item.beltTypeName = dictMatching(wx.getStorageSync('beltType') || [], item.beltType)
      })
      this.selectGoodsList = data.goodsList
      //详情页的物流单号不为null,才添加到 物流单号下拉框
      if(data.trackNumber != null && data.trackNumber != "null"){
        this.checkedGoodsList.push(data)
      }
      
    },
     getLogisicOrder () {
     
      home.getLogisicOrder().then(res =>{
        let { rows } = res
        this.checkedGoodsList = this.checkedGoodsList.concat(rows)
      }).catch()
      
    },
    PickerCodeChange (e) {
      this.indexCodePicker = e.mp.detail.value
      this.trackNumber = this.checkedGoodsList[e.mp.detail.value].trackNumber
      
     // 选择物流单号，过滤信息
      let list = this.checkedGoodsList.filter(item => item.trackNumber == this.trackNumber)
      let newList = []
      list[0].goodsList.map(item => {
        newList.push({
          ...item,
          open:false,
        goodsLevelName:dictMatching(wx.getStorageSync('goodsLevel') || [],item.goodsLevel),
        beltTypeName :dictMatching(wx.getStorageSync('beltType') || [], item.beltType),
        beginPicUrlList :item.beginPicUrl == null ? []: item.beginPicUrl.split(),
        endPicUrlList :item.endPicUrl == null ? []: item.endPicUrl.split(),
        logisticsGoods :1 //物流商品
        })
        
      })
      this.selectGoodsList = this.trackNumber != this.local.empty ? [...newList]:[...this.lockGoodsList,...newList]
    },
    pageReturn () {
        wx.setStorageSync('selectGoodsIdList', [])
    },
    changeLan (val,lang) {
      this.local = val
      this.lang = lang
    },
    async getCustomerList () {
      const {rows} = await home.getCustomerList()
      this.array = rows
    },
    PickerChange (e) {
      this.indexPicker = e.mp.detail.value
      this.customerId = this.array[e.mp.detail.value].customerId
      this.objSale.customerName = this.array[e.mp.detail.value].customerName
    },
    routerToUrl (url) {
      wx.navigateTo({
        url
      })
    },
    chooseImage (e) {
      var _this = this
      wx.chooseImage({
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          _this.files = _this.files.concat(res.tempFilePaths)
        }
      })
    },
    async getBelt () {
      const {rows} = await home.getBeltLevel({dictType: 'beltType'})
      this.arrayBelt = rows
    },
    async getLevel () {
      const {rows} = await home.getBeltLevel({dictType: 'goodsLevel'})
      this.arrayLevel = rows
    },
    predivImageBegin (e) {
      a = true
      previewImage(e)
    },
    predivImageEnd (e) {
      a = true
      previewImage(e)
    },
    async confirm () {
      if(this.objSale.saleOrderInvoice == null){
        //销售订单详情提交，需要判断 销售发票号必填，客户、商品已经在新增时判断
        wx.showToast({
          title: `${this.local.salesInvoiceNo}${this.local.required}`,
          icon: 'none',
          duration: 2000
        })
        return 
      }
      if(this.selectGoodsList.length == 0){
         wx.showToast({
          title: `${this.local.addSaleOrderTip}`,
          icon: 'none',
          duration: 2000
        })
        return 
      }
      this.warehouseId = [...new Set(this.warehouseId)]
      this.goodsId = [...new Set(this.goodsId)]
      this.weight = this.selectGoodsList.reduce((prev, next) =>{
        return prev + next.weight
      },0)
      let params = {
        id: this.getId, 
        weight: this.weight, 
        trackNumber: this.trackNumber == this.local.empty ? '':this.trackNumber, 
        submitType: this.submitType, 
        customerId: this.customerId, 
        customerName: this.objSale.customerName,
        warehouseId: this.warehouseId.join(), 
        goodsId: this.goodsId.join(), 
        goodsCount: this.goodsCount, 
        saleOrderInvoice: this.objSale.saleOrderInvoice, 
        invoiceDate: this.objSale.invoiceDate,
        paymentStatus: this.indexPayment == null? '':this.paymentStatusList[this.indexPayment].dictValue,
        totalPrice: this.objSale.totalPrice == null ? '':this.objSale.totalPrice,
        remark: this.remark, 
        goodList: JSON.stringify(this.selectGoodsList)
      }
      wx.showLoading({title: this.local.submitting})
      home.editSaleOrderList(params).then(res =>{
        wx.hideLoading()
        if(res.code != 0){
          wx.showToast({
            title: res.msg || 'error',
            icon: 'none',
            duration: 2000
          })
          return
        }
        if (wx.getStorageSync('selectGoodsIdList').length == 0) {
          wx.setStorageSync('selectGoodsIdList', [])
        }
        wx.navigateTo({
          url: '/packageA/pages/saleOrderList/index'
        })
      }).catch(err => {
        wx.hideLoading()
        wx.showToast({
          title: err || 'error',
          icon: 'none',
          duration: 2000
        })
      })
      // const data = await home.editSaleOrderList(params)
      // wx.showToast({
      //   title: data.msg,
      //   duration: 2000,
      //   icon: 'none'
      // })
      // if (wx.getStorageSync('selectGoodsIdList').length == 0) {
      //   wx.setStorageSync('selectGoodsIdList', [])
      // }
      // if (data.code == 0) {
      //   wx.navigateTo({
      //     url: '/packageA/pages/saleOrderList/index'
      //   })
      // }
    }
  },
  data () {
    return {
      lang: wx.getStorageSync('lang'),
      getId: 0,
      Shop: Shop.BASE_URL,
      mydata: {
        selectGoodsItem: {}
      },
      selectGoodsList: [],
      arrayLevel: [],
      arrayBelt: [],
      objSale: {},
      objSave: [],
      time: '',
      weight: 0,
      trackNumber: '',
      indexCodePicker: 0,
      codeArray: [],
      remark: '',
      saleOrderInvoice: '',
      invoiceDate: '',
      pdt: 66,
      local: wx.getStorageSync('local'),
      obj: [], // 放在缓存中的商品信息
      goodsId: [], // 可多个
      warehouseId: [], // 可多个
      customerId: '1',
      goodsCount: 1,
      submitType: 1, // 保存新增不用传,确定提交传1
      files: [],
      indexPicker: 0,
      array: ['美国', '中国', '巴西', '日本'],
      logs: [],
      fileList: [],
      enable: false,
      loggisticsNoEnable: false,
      lockGoodsList: [],
      lockTrackNumber: '',
      checkedGoodsList: [],
      indexPayment: null,
      paymentStatus: '',
      paymentStatusLabel: '',
      paymentStatusList: wx.getStorageSync('paymentStatus') 
    }
  },
  created () {
    this.getBelt()
    this.getLevel()
    // this.getLogisicOrder() // 物流单号列表
    this.getCustomerList() // 客户列表
  }
}
</script>

<style scoped lang="scss">
@import 'index';
.log-list {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
}

.log-item {
  margin: 10rpx;
}
</style>
